﻿using DesktopTool.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace DesktopTool.ViewControl
{
    /// <summary>
    /// 
    /// </summary>
    static class Serializer
    {
        public static string SAVE_CLEAN = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Desktoptool\";
        public static string SAVE_PATH = SAVE_CLEAN + @"IsolatedStore\";
        public const string AFBEELDINGEN_FOLDER = @"Afbeeldingen\";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        public static void checkAndCreateFolder(string path)
        {
            if (!System.IO.Directory.Exists(path))
                Directory.CreateDirectory(path + AFBEELDINGEN_FOLDER);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <param name="objectToSerialize"></param>
        public static void SerializeObject(string path, object objectToSerialize)
        {
            XmlSerializer serializer = new XmlSerializer(objectToSerialize.GetType());

            using (TextWriter writer = new StreamWriter(path))
            {
                serializer.Serialize(writer, objectToSerialize);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static object DeSerializeObject(string path)
        {
            object tmpObjects = null;

            string fileName = Path.GetFileName(path);

            if (fileName == "bezienswaardigheden.dat")
            {
                var serializer = new XmlSerializer(typeof(List<Bezienswaardigheid>));

                using (var stream = new FileStream(path, FileMode.Open))
                {
                    tmpObjects = serializer.Deserialize(stream) as List<Bezienswaardigheid>;
                }
            }
            else if (fileName == "routes.dat")
            {
                var serializer = new XmlSerializer(typeof(List<Route>));

                using (var stream = new FileStream(path, FileMode.Open))
                {
                    tmpObjects = serializer.Deserialize(stream) as List<Route>;
                }
            }

            return tmpObjects;
        }
    }
}
